package leetcode.offer;

import entity.ListNode;
import org.junit.Test;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 2021年11月21日 16:06:00
 */
public class offer22 {

    @Test
    public void test() {

        ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6, null))))));
        int k = 2;

        ListNode listNodeOne = new ListNode(1, new ListNode(2, null));
        ListNode kthFromEnd = getKthFromEnd(listNodeOne, k);
        System.out.println("test");
    }


    public ListNode getKthFromEnd(ListNode head, int k) {
        int n = 0;
        ListNode end;

        for (end = head; end != null; end = end.next) {
            n++;
        }
        int p = 1;
        while (head != null) {
            if (k == n) {
                return head;
            }
            if (k == n - p) {
                end = head.next;
            }
            p++;
            head = head.next;
        }
        return end;
    }


}
